"""
---------------------------------------------------------------------
- File: service.py
- Date: 2025/9/23
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description:
---------------------------------------------------------------------
"""

# model
from app.models.system_manage.user import User

# pydantic
from .schemas import UserIn, UserPwdIn

# 工具函数
from app.core.security import get_password_hash
from app.curd.orm_crud import OrmCRUD


class UserService:
    @staticmethod
    async def add_user(user_in: UserIn) -> User:
        user_in.password = get_password_hash(user_in.password)
        user = await OrmCRUD(User).create(**user_in.model_dump())
        return user

    @staticmethod
    async def delete_user(user_id: int) -> dict | None:
        result = await OrmCRUD(User).delete(user_id)
        return result

    @staticmethod
    async def batch_delete_user(ids: list[int | str]) -> dict:
        result = await OrmCRUD(User).batch_delete(ids)
        return result

    @staticmethod
    async def update_user(user_id: int, user_in: UserIn) -> User | None:
        user = await OrmCRUD(User).get(user_id)
        if user is None:
            return None
        user_in.password = get_password_hash(user_in.password)
        await OrmCRUD(User).update(user_in.model_dump(), user_id)
        # 重新查询更新后的用户信息
        new_user = await OrmCRUD(User).get(user_id)
        if new_user is None:
            return None
        return new_user

    @staticmethod
    async def update_user_password(user_id: int, user_pwd: UserPwdIn) -> User | None:
        user = await OrmCRUD(User).get(user_id)
        if user is None:
            return None
        user_pwd.password = get_password_hash(user_pwd.password.strip())
        await OrmCRUD(User).update(user_pwd.model_dump(), user_id)
        # 重新查询更新后的用户信息
        new_user = await OrmCRUD(User).get(user_id)
        if new_user is None:
            return None
        return new_user

    @staticmethod
    async def get_user(user_id: int) -> User | None:
        user = await OrmCRUD(User).get(user_id)
        if user is None:
            return None
        return user

    @staticmethod
    async def get_user_list(page: int = 1, page_size: int = 10) -> list[User]:
        users = await OrmCRUD(User).get_list(page=page, page_size=page_size)
        return users
